"""
添加素材页面

用于上传和添加新素材的页面
"""

import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from pathlib import Path
import threading
import sys
import os

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

from src.gui.main_app import BasePage
from src.gui.design_system import (DesignSystem, create_card_frame,
                                  create_primary_button, create_secondary_button,
                                  create_success_button, create_danger_button)


class AddMaterialPage(BasePage):
    """添加素材页面"""
    
    def __init__(self, parent, app):
        super().__init__(parent, app)
        self.selected_files = []
        self.upload_progress = {}
        
    def create_page(self):
        """创建页面内容"""
        self.frame = ttk.Frame(self.parent)
        
        # 页面标题
        self.create_header()
        
        # 商品选择区域
        self.create_product_selection()
        
        # 文件上传区域
        self.create_upload_area()
        
        # 文件列表区域
        self.create_file_list()
        
        # 控制按钮区域
        self.create_control_buttons()
        
        # 状态栏
        self.create_status_bar()
    
    def create_header(self):
        """创建页面标题"""
        header_frame = ttk.Frame(self.frame)
        header_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))

        # 标题区域
        title_container = ttk.Frame(header_frame)
        title_container.pack(side="left", fill="x", expand=True)

        title_label = ttk.Label(
            title_container,
            text="➕ 添加素材",
            style='Title.TLabel'
        )
        title_label.pack(side="left")

        # 副标题
        subtitle_label = ttk.Label(
            title_container,
            text="上传新的素材文件到系统",
            style='Muted.TLabel'
        )
        subtitle_label.pack(side="left", padx=(DesignSystem.SPACING['md'], 0))

        # 返回按钮
        back_btn = create_secondary_button(
            header_frame,
            text="← 返回列表",
            command=lambda: self.app.show_page("material_list")
        )
        back_btn.pack(side="right")
    
    def create_product_selection(self):
        """创建商品选择区域"""
        product_frame = create_card_frame(self.frame, "商品选择")
        product_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))

        # 商品选择行
        selection_frame = ttk.Frame(product_frame)
        selection_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))

        # 选择标签
        ttk.Label(selection_frame, text="关联商品:", style='Heading.TLabel').pack(side="left")

        # 商品下拉框
        self.product_var = tk.StringVar(value="请选择商品...")
        self.product_combo = ttk.Combobox(
            selection_frame,
            textvariable=self.product_var,
            values=[
                "请选择商品...",
                "🎽 时尚T恤 - SKU001",
                "👟 运动鞋 - SKU002",
                "👖 休闲裤 - SKU003",
                "👗 夏季连衣裙 - SKU004",
                "👔 商务衬衫 - SKU005"
            ],
            width=35,
            state="readonly"
        )
        self.product_combo.pack(side="left", padx=(DesignSystem.SPACING['md'], DesignSystem.SPACING['lg']))

        # 新建商品按钮
        new_product_btn = create_primary_button(
            selection_frame,
            text="+ 新建商品",
            command=self.create_new_product
        )
        new_product_btn.pack(side="left")

        # 商品信息显示区域
        info_frame = ttk.Frame(product_frame)
        info_frame.pack(fill="x")

        # 信息图标和文本
        info_container = ttk.Frame(info_frame)
        info_container.pack(side="left")

        info_icon = ttk.Label(info_container, text="💡", font=(DesignSystem.FONTS['family_primary'], 14))
        info_icon.pack(side="left")

        self.product_info_label = ttk.Label(
            info_container,
            text="请选择商品以查看详细信息和关联设置",
            style='Muted.TLabel'
        )
        self.product_info_label.pack(side="left", padx=(DesignSystem.SPACING['sm'], 0))
    
    def create_upload_area(self):
        """创建文件上传区域"""
        upload_frame = create_card_frame(self.frame, "文件上传")
        upload_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))

        # 上传区域容器
        upload_container = ttk.Frame(upload_frame)
        upload_container.pack(fill="x")

        # 上传区域 - 使用渐变色背景效果
        self.drop_area = ttk.Frame(upload_container, relief="solid", borderwidth=2)
        self.drop_area.pack(fill="x", pady=DesignSystem.SPACING['md'])
        self.drop_area.configure(style='Card.TFrame')

        # 内容区域
        content_area = ttk.Frame(self.drop_area, padding=DesignSystem.SPACING['xxxl'])
        content_area.pack(fill="x")

        # 上传图标
        icon_label = ttk.Label(
            content_area,
            text="☁️",
            font=(DesignSystem.FONTS['family_primary'], 48),
            foreground=DesignSystem.COLORS['primary']
        )
        icon_label.pack(pady=(0, DesignSystem.SPACING['lg']))

        # 主要提示文字
        main_text = ttk.Label(
            content_area,
            text="点击选择文件或拖拽文件到此处",
            style='Heading.TLabel'
        )
        main_text.pack(pady=(0, DesignSystem.SPACING['sm']))

        # 支持格式提示
        hint_text = ttk.Label(
            content_area,
            text="支持视频 (MP4, AVI, MOV)、图片 (JPG, PNG, GIF)、音频 (MP3, WAV) 文件",
            style='Muted.TLabel'
        )
        hint_text.pack(pady=(0, DesignSystem.SPACING['xl']))

        # 选择文件按钮
        select_btn = create_primary_button(
            content_area,
            text="📂 选择文件",
            command=self.select_files
        )
        select_btn.pack()

        # 或者分隔线
        separator_frame = ttk.Frame(content_area)
        separator_frame.pack(fill="x", pady=DesignSystem.SPACING['lg'])

        ttk.Separator(separator_frame, orient='horizontal').pack(side="left", fill="x", expand=True)
        ttk.Label(separator_frame, text=" 或者 ", style='Muted.TLabel').pack(side="left")
        ttk.Separator(separator_frame, orient='horizontal').pack(side="left", fill="x", expand=True)

        # 拖拽提示
        drag_hint = ttk.Label(
            content_area,
            text="🖱️ 直接拖拽文件到此区域",
            style='Muted.TLabel'
        )
        drag_hint.pack()

        # 绑定点击事件
        self.drop_area.bind("<Button-1>", lambda e: self.select_files())
        content_area.bind("<Button-1>", lambda e: self.select_files())
        icon_label.bind("<Button-1>", lambda e: self.select_files())
        main_text.bind("<Button-1>", lambda e: self.select_files())

        # 添加悬停效果
        self._setup_hover_effects()

    def _setup_hover_effects(self):
        """设置悬停效果"""
        def on_enter(event):
            self.drop_area.configure(relief="solid", borderwidth=3)

        def on_leave(event):
            self.drop_area.configure(relief="solid", borderwidth=2)

        self.drop_area.bind("<Enter>", on_enter)
        self.drop_area.bind("<Leave>", on_leave)
    
    def create_file_list(self):
        """创建文件列表区域"""
        list_frame = ttk.LabelFrame(self.frame, text="待上传文件", padding="10")
        list_frame.pack(fill="both", expand=True, pady=(0, 20))
        
        # 创建Treeview
        columns = ('name', 'size', 'type', 'category', 'progress')
        self.file_tree = ttk.Treeview(list_frame, columns=columns, show='headings', height=8)
        
        # 设置列标题和宽度
        column_config = {
            'name': ('文件名', 250),
            'size': ('大小', 100),
            'type': ('类型', 80),
            'category': ('分类', 120),
            'progress': ('进度', 100)
        }
        
        for col, (title, width) in column_config.items():
            self.file_tree.heading(col, text=title)
            self.file_tree.column(col, width=width)
        
        # 滚动条
        scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=self.file_tree.yview)
        self.file_tree.configure(yscrollcommand=scrollbar.set)
        
        # 布局
        self.file_tree.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
        
        # 绑定右键菜单
        self.file_tree.bind("<Button-3>", self.show_file_context_menu)
        
        # 空状态提示
        self.empty_label = ttk.Label(
            list_frame,
            text="暂无文件，请点击上方区域选择文件",
            foreground="gray"
        )
        self.empty_label.place(relx=0.5, rely=0.5, anchor="center")
    
    def create_control_buttons(self):
        """创建控制按钮区域"""
        button_frame = ttk.Frame(self.frame)
        button_frame.pack(fill="x", pady=(0, 20))
        
        # 左侧按钮
        left_frame = ttk.Frame(button_frame)
        left_frame.pack(side="left")
        
        clear_btn = ttk.Button(
            left_frame,
            text="🗑️ 清空列表",
            command=self.clear_file_list
        )
        clear_btn.pack(side="left", padx=(0, 10))
        
        batch_btn = ttk.Button(
            left_frame,
            text="⚙️ 批量设置",
            command=self.batch_settings
        )
        batch_btn.pack(side="left")
        
        # 右侧按钮
        right_frame = ttk.Frame(button_frame)
        right_frame.pack(side="right")
        
        self.pause_btn = ttk.Button(
            right_frame,
            text="⏸️ 暂停",
            command=self.pause_upload,
            state="disabled"
        )
        self.pause_btn.pack(side="right", padx=(10, 0))
        
        self.upload_btn = ttk.Button(
            right_frame,
            text="🚀 开始上传",
            command=self.start_upload
        )
        self.upload_btn.pack(side="right")
    
    def create_status_bar(self):
        """创建状态栏"""
        status_frame = ttk.Frame(self.frame)
        status_frame.pack(fill="x")
        
        # 状态文本
        self.status_var = tk.StringVar(value="就绪")
        status_label = ttk.Label(status_frame, textvariable=self.status_var)
        status_label.pack(side="left")
        
        # 进度条
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(
            status_frame,
            variable=self.progress_var,
            maximum=100,
            length=300
        )
        self.progress_bar.pack(side="right")
    
    def select_files(self):
        """选择文件"""
        file_types = [
            ("所有支持的文件", "*.mp4 *.avi *.mov *.mkv *.jpg *.jpeg *.png *.gif *.mp3 *.wav *.m4a"),
            ("视频文件", "*.mp4 *.avi *.mov *.mkv"),
            ("图片文件", "*.jpg *.jpeg *.png *.gif"),
            ("音频文件", "*.mp3 *.wav *.m4a"),
            ("所有文件", "*.*")
        ]
        
        files = filedialog.askopenfilenames(
            title="选择素材文件",
            filetypes=file_types
        )
        
        if files:
            self.add_files(files)
    
    def add_files(self, file_paths):
        """添加文件到列表"""
        for file_path in file_paths:
            if file_path not in [f['path'] for f in self.selected_files]:
                file_info = self.get_file_info(file_path)
                self.selected_files.append(file_info)
        
        self.update_file_list()
        self.update_status()
    
    def get_file_info(self, file_path):
        """获取文件信息"""
        path = Path(file_path)
        size = path.stat().st_size
        
        # 确定文件类型
        ext = path.suffix.lower()
        if ext in ['.mp4', '.avi', '.mov', '.mkv']:
            file_type = '视频'
            category = 'AI素材'  # 默认分类
        elif ext in ['.jpg', '.jpeg', '.png', '.gif']:
            file_type = '图片'
            category = '产品展示'
        elif ext in ['.mp3', '.wav', '.m4a']:
            file_type = '音频'
            category = '背景音乐'
        else:
            file_type = '其他'
            category = '未分类'
        
        return {
            'path': file_path,
            'name': path.name,
            'size': self.format_file_size(size),
            'type': file_type,
            'category': category,
            'progress': 0
        }
    
    def format_file_size(self, size_bytes):
        """格式化文件大小"""
        if size_bytes == 0:
            return "0 B"
        
        size_names = ["B", "KB", "MB", "GB"]
        i = 0
        size = float(size_bytes)
        
        while size >= 1024.0 and i < len(size_names) - 1:
            size /= 1024.0
            i += 1
        
        return f"{size:.1f} {size_names[i]}"
    
    def update_file_list(self):
        """更新文件列表显示"""
        # 清空现有项目
        for item in self.file_tree.get_children():
            self.file_tree.delete(item)
        
        # 隐藏/显示空状态提示
        if self.selected_files:
            self.empty_label.place_forget()
        else:
            self.empty_label.place(relx=0.5, rely=0.5, anchor="center")
            return
        
        # 添加文件项目
        for file_info in self.selected_files:
            # 文件类型图标
            type_icons = {
                '视频': '🎬',
                '图片': '🖼️',
                '音频': '🎵',
                '其他': '📄'
            }
            icon = type_icons.get(file_info['type'], '📄')
            
            # 进度显示
            progress = file_info['progress']
            if progress == 0:
                progress_text = "待上传"
            elif progress == 100:
                progress_text = "已完成"
            else:
                progress_text = f"{progress}%"
            
            self.file_tree.insert('', 'end', values=(
                f"{icon} {file_info['name']}",
                file_info['size'],
                file_info['type'],
                file_info['category'],
                progress_text
            ))
    
    def show_file_context_menu(self, event):
        """显示文件右键菜单"""
        item = self.file_tree.identify_row(event.y)
        if item:
            self.file_tree.selection_set(item)
            
            context_menu = tk.Menu(self.frame, tearoff=0)
            context_menu.add_command(label="修改分类", command=self.change_category)
            context_menu.add_command(label="查看详情", command=self.view_file_details)
            context_menu.add_separator()
            context_menu.add_command(label="从列表移除", command=self.remove_file)
            
            context_menu.tk_popup(event.x_root, event.y_root)
    
    def update_status(self):
        """更新状态显示"""
        file_count = len(self.selected_files)
        if file_count == 0:
            self.status_var.set("就绪")
        else:
            total_size = sum(Path(f['path']).stat().st_size for f in self.selected_files)
            size_text = self.format_file_size(total_size)
            self.status_var.set(f"已选择 {file_count} 个文件，总大小 {size_text}")
    
    def create_new_product(self):
        """创建新商品"""
        messagebox.showinfo("提示", "新商品创建功能开发中...")
    
    def clear_file_list(self):
        """清空文件列表"""
        if self.selected_files:
            if messagebox.askyesno("确认", "确定要清空所有文件吗？"):
                self.selected_files.clear()
                self.update_file_list()
                self.update_status()
    
    def batch_settings(self):
        """批量设置"""
        messagebox.showinfo("提示", "批量设置功能开发中...")
    
    def start_upload(self):
        """开始上传"""
        if self.product_var.get() == "请选择商品...":
            messagebox.showwarning("警告", "请先选择商品！")
            return
        
        if not self.selected_files:
            messagebox.showwarning("警告", "请先选择要上传的文件！")
            return
        
        # 开始上传
        self.upload_btn.configure(state="disabled")
        self.pause_btn.configure(state="normal")
        
        # 模拟上传过程
        upload_thread = threading.Thread(target=self.simulate_upload)
        upload_thread.daemon = True
        upload_thread.start()
    
    def simulate_upload(self):
        """模拟上传过程"""
        total_files = len(self.selected_files)
        
        for i, file_info in enumerate(self.selected_files):
            # 模拟上传进度
            for progress in range(0, 101, 20):
                file_info['progress'] = progress
                self.frame.after(0, self.update_file_list)
                
                # 更新总进度
                overall_progress = ((i * 100 + progress) / (total_files * 100)) * 100
                self.frame.after(0, lambda p=overall_progress: self.progress_var.set(p))
                
                threading.Event().wait(0.2)
        
        # 上传完成
        self.frame.after(0, self.upload_completed)
    
    def upload_completed(self):
        """上传完成"""
        self.upload_btn.configure(state="normal")
        self.pause_btn.configure(state="disabled")
        self.status_var.set("上传完成！")
        messagebox.showinfo("成功", "所有文件上传完成！")
    
    def pause_upload(self):
        """暂停上传"""
        messagebox.showinfo("提示", "暂停上传功能开发中...")
    
    def change_category(self):
        """修改分类"""
        messagebox.showinfo("提示", "修改分类功能开发中...")
    
    def view_file_details(self):
        """查看文件详情"""
        messagebox.showinfo("提示", "查看详情功能开发中...")
    
    def remove_file(self):
        """从列表移除文件"""
        selection = self.file_tree.selection()
        if selection:
            item = selection[0]
            index = self.file_tree.index(item)
            if 0 <= index < len(self.selected_files):
                self.selected_files.pop(index)
                self.update_file_list()
                self.update_status()
